package com.example.denglu.servlet;

import com.example.denglu.service.UserService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import javax.servlet.ServletException;

@WebServlet("/setPassword")
public class SetPasswordServlet extends HttpServlet {
    
    private boolean isValidPassword(String password) {
        // 检查密码是否同时包含字母和数字，且长度至少为10位
        return password != null && 
               password.length() >= 10 && 
               password.matches(".*[a-zA-Z].*") && 
               password.matches(".*[0-9].*");
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
        HttpSession session = request.getSession();
        String phone = (String) session.getAttribute("phone");
        String openid = (String) session.getAttribute("wechat_openid");
        String password = request.getParameter("password");
        
        System.out.println("设置密码 - phone: " + phone + ", openid: " + openid);
        
        // 参数验证
        if ((phone == null || phone.trim().isEmpty()) && (openid == null || openid.trim().isEmpty())) {
            response.getWriter().write("{\"success\":false,\"message\":\"请先登录\"}");
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            response.getWriter().write("{\"success\":false,\"message\":\"密码不能为空\"}");
            return;
        }
        
        // 密码格式验证
        if (!isValidPassword(password)) {
            response.getWriter().write("{\"success\":false,\"message\":\"密码必须包含字母和数字，且长度至少10位\"}");
            return;
        }
        
        boolean isSuccess;
        if (openid != null) {
            // 微信用户设置密码
            isSuccess = UserService.setWeChatUserPassword(openid, password);
        } else if (phone != null) {
            // 手机号用户设置密码
            isSuccess = UserService.setPassword(phone, password);
        } else {
            isSuccess = false;
        }
        
        if (isSuccess) {
            // 更新session中的用户信息
            session.setAttribute("hasPassword", true);
        }
        
        response.getWriter().write("{\"success\":" + isSuccess + 
                ",\"message\":\"" + (isSuccess ? "密码设置成功" : "密码设置失败") + "\"}");
    }
} 